import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:elephant_fish/http/core/hi_net.dart';
import 'package:elephant_fish/http/request/base_request.dart';
import 'package:elephant_fish/http/request/edit_message_status.dart';
import 'package:elephant_fish/http/request/message_count_request.dart';
import 'package:elephant_fish/http/request/system_get_message.dart';
import 'package:elephant_fish/http/request/user_info_request.dart';
import 'package:elephant_fish/model/message_count_entity.dart';
import 'package:elephant_fish/model/message_entity.dart';
import 'package:elephant_fish/model/user_info_entity.dart';
import 'package:elephant_fish/tencentImPlugin/common/colors.dart';
import 'package:elephant_fish/tencentImPlugin/common/hexToColor.dart';
import 'package:elephant_fish/tencentImPlugin/conversion/conversion.dart';
import 'package:elephant_fish/tencentImPlugin/pages/message/message.dart';
import 'package:elephant_fish/tencentImPlugin/provider/conversion.dart';
import 'package:elephant_fish/tencentImPlugin/provider/user.dart';
import 'package:elephant_fish/tencentImPlugin/utils/GenerateTestUserSig.dart';
import 'package:elephant_fish/tencentImPlugin/utils/config.dart';
import 'package:elephant_fish/tencentImPlugin/utils/toast.dart';
import 'package:elephant_fish/util/TxUtils.dart';
import 'package:elephant_fish/util/size_util.dart';
import 'package:elephant_fish/widget/message_list.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tencent_im_sdk_plugin/enum/message_elem_type.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_conversation.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_conversation_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';
import 'package:tencent_im_sdk_plugin/enum/V2TimAdvancedMsgListener.dart';
import 'package:tencent_im_sdk_plugin/enum/V2TimConversationListener.dart';
import 'package:tencent_im_sdk_plugin/enum/V2TimFriendshipListener.dart';
import 'package:tencent_im_sdk_plugin/enum/V2TimGroupListener.dart';
import 'package:tencent_im_sdk_plugin/enum/V2TimSDKListener.dart';
import 'package:tencent_im_sdk_plugin/enum/V2TimSignalingListener.dart';
import 'package:tencent_im_sdk_plugin/enum/V2TimSimpleMsgListener.dart';
import 'package:tencent_im_sdk_plugin/enum/log_level.dart';
import 'package:tencent_im_sdk_plugin/manager/v2_tim_manager.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_application.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_group_application_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message_receipt.dart';
import 'package:elephant_fish/tencentImPlugin/pages/login/login.dart';
import 'package:elephant_fish/tencentImPlugin/provider/currentMessageList.dart';
import 'package:elephant_fish/tencentImPlugin/provider/friend.dart';
import 'package:elephant_fish/tencentImPlugin/provider/friendApplication.dart';
import 'package:elephant_fish/tencentImPlugin/provider/groupApplication.dart';

import 'login_page.dart';

class MessagePage extends StatefulWidget {
  const MessagePage({Key key}) : super(key: key);

  @override
  _MessagePageState createState() => _MessagePageState();
}

class _MessagePageState extends State<MessagePage> {

  List<MessageEntity> messageList = [];
  bool _loading = false;
  int pageIndex = 1;
  UserInfoEntity userInfoEntity;
  MessageCountEntity messageCountEntity;
  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    getInitData();
    _scrollController.addListener(() {
      var dis = _scrollController.position.maxScrollExtent -
          _scrollController.position.pixels;
      //当距离底部不足300时加载更多
      if (dis < 300 && !_loading) {
        _loadData(loadMore: true);
      }
    });
    _loadData();
    getMessageCount();
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    List<V2TimConversation> conversionList = Provider.of<ConversionModel>(
      context,
      listen: true,
    ).conversionList;
    return Scaffold(
        backgroundColor: Color(0xff140c3d),
        appBar: AppBar(
          automaticallyImplyLeading: false,
          backgroundColor: Color(0xff140c3d),
          centerTitle: true,
          title: Text(
            '消息',
            style:
                TextStyle(fontSize: SizeUtil.px(32), color: Color(0xfff3f3f3)),
          ),
        ),
        body: SingleChildScrollView(
          child: Column(
            children: [
              Align(
                alignment: Alignment.topCenter,
                child: Padding(
                  padding: EdgeInsets.only(top: SizeUtil.px(32)),
                  child: Container(
                    width: SizeUtil.px(694),
                    height: SizeUtil.px(211),
                    decoration: BoxDecoration(
                      color: Color(0xff221a46),
                      //设置四周圆角 角度
                      borderRadius:
                          BorderRadius.all(Radius.circular(SizeUtil.px(23))),
                    ),
                    child: Stack(
                      children: [

                        Align(
                            alignment: Alignment.topLeft,
                            child: Padding(
                                padding: EdgeInsets.only(
                                    top: SizeUtil.px(36), left: SizeUtil.px(83)),
                                child:  InkWell(
                                    child:Container(
                                  width: SizeUtil.px(92),
                                  height: SizeUtil.px(92),
                                  child: Image.asset(
                                    'assets/images/system_message.png',
                                  ),
                                ), onTap: (){
                                  messageList = [];
                                  _loadData(type: 6);
                                },),
                          ),

                        ),
                        messageCountEntity == null ? Container(width: 0,height: 0,) : messageCountEntity.system != 0 ?
                        Align(
                          alignment: Alignment.topLeft,
                          child: Padding(
                            padding: EdgeInsets.only(top: 17.15,left: 80),
                            child: Container(
                              width: 19.5,
                              height: 19.5,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.all(Radius.circular(10)),
                                color: Color(0xfff25045),
                              ),
                              child: Center(
                                child: Text(messageCountEntity.system.toString(),style: TextStyle(fontSize: 13.5,color: Color(0xfff3f3f3)),),
                              ),
                            ),
                          ),
                        ) : Container(width: 0,height: 0,),
                        Align(
                          alignment: Alignment.topLeft,
                          child: Padding(
                              padding: EdgeInsets.only(
                                  top: SizeUtil.px(138), left: SizeUtil.px(81)),
                              child: Text(
                                '系统消息',
                                style: TextStyle(
                                    fontSize: SizeUtil.px(25),
                                    color: Color(0xfff3f3f3)),
                              )),
                        ),
                        Align(
                            alignment: Alignment.topCenter,
                            child:  Padding(
                                padding: EdgeInsets.only(top: SizeUtil.px(36)),
                                child: InkWell(
                                    child: Container(
                                  width: SizeUtil.px(92),
                                  height: SizeUtil.px(92),
                                  child: Image.asset(
                                    'assets/images/recharge_message.png',
                                  ),
                                ), onTap: (){
                                  messageList = [];
                                  _loadData(type: 4);
                                },),

                          ),

                        ),
                        messageCountEntity == null ? Container(width: 0,height: 0,) : messageCountEntity.recharge != 0 ?
                        Align(
                          alignment: Alignment.topCenter,
                          child: Padding(
                            padding: EdgeInsets.only(top: 17.15,left: 40),
                            child: Container(
                              width: 19.5,
                              height: 19.5,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.all(Radius.circular(10)),
                                color: Color(0xfff25045),
                              ),
                              child: Center(
                                child: Text(messageCountEntity.recharge.toString(),style: TextStyle(fontSize: 13.5,color: Color(0xfff3f3f3)),),
                              ),
                            ),
                          ),
                        ) : Container(width: 0,height: 0,),
                        Align(
                          alignment: Alignment.topCenter,
                          child: Padding(
                              padding: EdgeInsets.only(top: SizeUtil.px(138)),
                              child: Text(
                                '充值消息',
                                style: TextStyle(
                                    fontSize: SizeUtil.px(25),
                                    color: Color(0xfff3f3f3)),
                              )),
                        ),
                       Align(
                            alignment: Alignment.topRight,
                            child: Padding(
                                padding: EdgeInsets.only(
                                    top: SizeUtil.px(36), right: SizeUtil.px(83)),
                                child:  InkWell(
                                    child: Container(
                                  width: SizeUtil.px(92),
                                  height: SizeUtil.px(92),
                                  child: Image.asset(
                                    'assets/images/online_message.png',
                                  ),
                                ), onTap: (){
                                  messageList = [];
                                  _loadData(type: 5);
                                },),
                          ),

                        ),
                        messageCountEntity == null ? Container(width: 0,height: 0,) : messageCountEntity.online != 0 ?
                        Align(
                          alignment: Alignment.topRight,
                          child: Padding(
                            padding: EdgeInsets.only(top: 17.15,right: 40),
                            child: Container(
                              width: 19.5,
                              height: 19.5,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.all(Radius.circular(10)),
                                color: Color(0xfff25045),
                              ),
                              child: Center(
                                child: Text(messageCountEntity.online.toString(),style: TextStyle(fontSize: 13.5,color: Color(0xfff3f3f3)),),
                              ),
                            ),
                          ),
                        ) : Container(width: 0,height: 0,),
                        Align(
                          alignment: Alignment.topRight,
                          child: Padding(
                              padding: EdgeInsets.only(
                                  top: SizeUtil.px(138),
                                  right: SizeUtil.px(81)),
                              child: Text(
                                '上线消息',
                                style: TextStyle(
                                    fontSize: SizeUtil.px(25),
                                    color: Color(0xfff3f3f3)),
                              )),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              SizedBox(
                height: 400,
                child:
                ListView.builder(
                    itemCount: messageList.length,
                    itemBuilder: (context,index){
                      return MessageList(message: messageList[index],);
                    }
                ),
              ),



              // SingleChildScrollView(child:
              // conversionList == null || conversionList.isEmpty
              //     ? Center(
              //   child: Text(
              //     "暂无会话",
              //     style: TextStyle(
              //       color: CommonColors.getTextWeakColor(),
              //     ),
              //   ),
              // )
              //     : ListView(
              //   shrinkWrap: true,
              //   children: conversionList.map((e) {
              //     if (e.lastMessage == null ||
              //         e.lastMessage.msgID == '') {
              //       return Container();
              //     }
              //     return Container(
              //       height: 70,
              //       child: Slidable(
              //         key: Key(e.conversationID),
              //         actionPane: SlidableDrawerActionPane(),
              //         actionExtentRatio: 0.25,
              //         child: ConversionItem(
              //           name: e.showName,
              //           faceUrl: e.faceUrl != ''
              //               ? 'http://119.28.131.94:82' + e.faceUrl
              //               : e.faceUrl,
              //           lastMessage: e.lastMessage,
              //           unreadCount: e.unreadCount,
              //           type: e.type,
              //           conversationID: e.conversationID,
              //           userID: e.userID,
              //         ),
              //         secondaryActions: <Widget>[
              //           IconSlideAction(
              //             caption: '删除',
              //             color: Colors.red,
              //             icon: Icons.delete,
              //             onTap: () {
              //               TencentImSDKPlugin.v2TIMManager
              //                   .getConversationManager()
              //                   .deleteConversation(
              //                 conversationID: e.conversationID,
              //               )
              //                   .then((value) {
              //                 if (value.code == 0) {
              //                   Utils.toast("删除成功");
              //                   Provider.of<ConversionModel>(context,
              //                       listen: false)
              //                       .removeConversionByConversationId(
              //                       e.conversationID);
              //                 } else {
              //                   Utils.toast(
              //                       "删除失败 ${value.code} ${value.desc}");
              //                 }
              //               });
              //             },
              //             closeOnTap: true,
              //           ),
              //         ],
              //       ),
              //     );
              //   }).toList(),
              // ),
              // )
            ],
          ),
        ));
  }

  Future<void> getInitData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = UserInfoRequest();
    request.add('type', 2).addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    }
    setState(() {
      userInfoEntity = UserInfoEntity.fromJson(
          new Map<String, dynamic>.from(result['data']));
    });
    initSDK();
  }

  getMessage() async {
    V2TimValueCallback<V2TimConversationResult> data = await TencentImSDKPlugin
        .v2TIMManager
        .getConversationManager()
        .getConversationList(count: 100, nextSeq: "0");
    print("当前会话长度${data.data.conversationList.length}");

    List<V2TimConversation> newList =
        data.data.conversationList.cast<V2TimConversation>();
    Provider.of<ConversionModel>(
      context,
      listen: false,
    ).setConversionList(newList);
  }

  initSDK() async {
    V2TIMManager timManager = TencentImSDKPlugin.v2TIMManager;
    await timManager.initSDK(
      sdkAppID: Config.sdkappid,
      loglevel: LogLevel.V2TIM_LOG_DEBUG,
      listener: new V2TimSDKListener(
        onConnectFailed: (code, error) {},
        onConnectSuccess: () {},
        onConnecting: () {},
        onKickedOffline: () {
          onKickedOffline();
        },
        onSelfInfoUpdated: (info) {
          onSelfInfoUpdated();
        },
        onUserSigExpired: () {},
      ),
    );

    print("initSDK");

    //简单监听
    timManager.addSimpleMsgListener(
      listener: new V2TimSimpleMsgListener(
        onRecvC2CCustomMessage: (msgID, sender, customData) {},
        onRecvC2CTextMessage: (msgID, userInfo, text) {},
        onRecvGroupCustomMessage: (msgID, groupID, sender, customData) {},
        onRecvGroupTextMessage: (msgID, groupID, sender, customData) {},
      ),
    );

    //群组监听
    timManager.setGroupListener(
      listener: new V2TimGroupListener(
        onApplicationProcessed: (groupID, opUser, isAgreeJoin, opReason) {},
        onGrantAdministrator: (groupID, opUser, memberList) {},
        onGroupAttributeChanged: (groupID, groupAttributeMap) {},
        onGroupCreated: (groupID) {},
        onGroupDismissed: (groupID, opUser) {},
        onGroupInfoChanged: (groupID, changeInfos) {},
        onGroupRecycled: (groupID, opUser) {},
        onMemberEnter: (groupID, memberList) {
          onReceiveJoinApplicationonMemberEnter();
        },
        onMemberInfoChanged: (groupID, v2TIMGroupMemberChangeInfoList) {},
        onMemberInvited: (groupID, opUser, memberList) {},
        onMemberKicked: (groupID, opUser, memberList) {},
        onMemberLeave: (groupID, member) {},
        onQuitFromGroup: (groupID) {},
        onReceiveJoinApplication: (groupID, member, opReason) {
          onReceiveJoinApplicationonMemberEnter();
        },
        onReceiveRESTCustomData: (groupID, customData) {},
        onRevokeAdministrator: (groupID, opUser, memberList) {},
      ),
    );
    //高级消息监听
    timManager.getMessageManager().addAdvancedMsgListener(
      listener: new V2TimAdvancedMsgListener(
        onRecvC2CReadReceipt: (receiptList) {
          onRecvC2CReadReceipt(receiptList);
        },
        onRecvMessageRevoked: (msgID) {},
        onRecvNewMessage: (msg) {
          onRecvNewMessage(msg);
        },
        onSendMessageProgress: (message, progress) {
          onSendMessageProgress(message, progress);
        },
      ),
    );

    timManager.getFriendshipManager().setFriendListener(
      listener: new V2TimFriendshipListener(
        onBlackListAdd: (infoList) {},
        onBlackListDeleted: (userList) {
          onFriendListAddedonFriendListDeletedonFriendInfoChangedonBlackListDeleted();
        },
        onFriendApplicationListAdded: (applicationList) {
          onFriendApplicationListAdded(applicationList);
        },
        onFriendApplicationListDeleted: (userIDList) {},
        onFriendApplicationListRead: () {},
        onFriendInfoChanged: (infoList) {
          onFriendListAddedonFriendListDeletedonFriendInfoChangedonBlackListDeleted();
        },
        onFriendListAdded: (users) {
          onFriendListAddedonFriendListDeletedonFriendInfoChangedonBlackListDeleted();
        },
        onFriendListDeleted: (userList) {
          onFriendListAddedonFriendListDeletedonFriendInfoChangedonBlackListDeleted();
        },
      ),
    );
    //会话监听
    timManager.getConversationManager().setConversationListener(
      listener: new V2TimConversationListener(
        onConversationChanged: (conversationList) {
          try {
            Provider.of<ConversionModel>(context, listen: false)
                .setConversionList(conversationList);
            //如果当前会话在使用中，也更新一下

          } catch (e) {}
        },
        onNewConversation: (conversationList) {
          try {
            Provider.of<ConversionModel>(context, listen: false)
                .setConversionList(conversationList);
            //如果当前会话在使用中，也更新一下

          } catch (e) {}
        },
        onSyncServerFailed: () {},
        onSyncServerFinish: () {},
        onSyncServerStart: () {},
      ),
    );
    timManager.getSignalingManager().addSignalingListener(
      listener: new V2TimSignalingListener(
        onInvitationCancelled: (inviteID, inviter, data) {},
        onInvitationTimeout: (inviteID, inviteeList) {},
        onInviteeAccepted: (inviteID, invitee, data) {},
        onInviteeRejected: (inviteID, invitee, data) {},
        onReceiveNewInvitation:
            (inviteID, inviter, groupID, inviteeList, data) {},
      ),
    );
    print("初始化完成了");
    imLogin();
  }

  imLogin(){
    if (userInfoEntity.userId == '') {
      return;
    }
    GenerateTestUserSig usersig =
    new GenerateTestUserSig(
      sdkappid: Config.sdkappid,
      key: Config.key,
    );
    String pwdStr = usersig.genSig(
        identifier: userInfoEntity.userId,
        expire: 86400);
    // 按理来说这里是存
    TencentImSDKPlugin.v2TIMManager
        .login(
      userID: userInfoEntity.userId,
      userSig: pwdStr,
    )
        .then((res) async {
      if (res.code == 0) {
        V2TimValueCallback<
            List<V2TimUserFullInfo>> infos =
        await TencentImSDKPlugin
            .v2TIMManager
            .getUsersInfo(userIDList: [
          userInfoEntity.userId
        ]);

        if (infos.code == 0) {
          Provider.of<UserModel>(context,
              listen: false)
              .setInfo(infos.data[0]);
          getMessage();
        }
        Future<SharedPreferences> _prefs =
        SharedPreferences.getInstance();
        SharedPreferences prefs = await _prefs;
        prefs.setString("flutter_userID",
            userInfoEntity.userId);

        // 加个群
        await TencentImSDKPlugin.v2TIMManager
            .joinGroup(
          groupID: "@TGS#2FGN3DHHB",
          message: "大家好",
        );
      } else {
        Utils.toast("${res.code} ${res.desc}");
      }
    });
  }

  void onSelfInfoUpdated() async {
    //自己信息更新，从新获取自己的信息；
    V2TimValueCallback<String> usercallback =
    await TencentImSDKPlugin.v2TIMManager.getLoginUser();
    V2TimValueCallback<List<V2TimUserFullInfo>> infos = await TencentImSDKPlugin
        .v2TIMManager
        .getUsersInfo(userIDList: [usercallback.data]);
    if (infos.code == 0) {
      Provider.of<UserModel>(context, listen: false).setInfo(infos.data[0]);
    }
  }

  void onKickedOffline() async {
// 被踢下线
    // 清除本地缓存，回到登录页TODO
    try {
      Provider.of<ConversionModel>(context, listen: false).clear();
      Provider.of<UserModel>(context, listen: false).clear();
      Provider.of<CurrentMessageListModel>(context, listen: false).clear();
      Provider.of<FriendListModel>(context, listen: false).clear();
      Provider.of<FriendApplicationModel>(context, listen: false).clear();
      Provider.of<GroupApplicationModel>(context, listen: false).clear();
      // 去掉存的一些数据
      Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
      SharedPreferences prefs = await _prefs;
      prefs.remove('token');
      prefs.remove('sessionId');
      prefs.remove('phone');
      prefs.remove('code');
    } catch (err) {
      print("someError");
      print(err);
    }
    print("被踢下线了");
    Navigator.of(context).pushAndRemoveUntil(
      MaterialPageRoute(builder: (BuildContext context) => LoginPage1()),
      ModalRoute.withName('/'),
    );
  }

  void onReceiveJoinApplicationonMemberEnter() async {
    V2TimValueCallback<V2TimGroupApplicationResult> res =
    await TencentImSDKPlugin.v2TIMManager
        .getGroupManager()
        .getGroupApplicationList();
    if (res.code == 0) {
      if (res.code == 0) {
        if (res.data.groupApplicationList.length > 0) {
          Provider.of<GroupApplicationModel>(context, listen: false)
              .setGroupApplicationResult(res.data.groupApplicationList);
        }
      }
    } else {
      print("获取加群申请失败${res.desc}");
    }
  }

  void onRecvNewMessage(V2TimMessage message) {
    try {
      List<V2TimMessage> messageList = List.empty(growable: true);

      messageList.add(message);

      print("c2c_${message.sender}");
      String key;
      if (message.groupID == null) {
        key = "c2c_${message.sender}";
      } else {
        key = "group_${message.groupID}";
      }
      print("conterkey_$key");
      Provider.of<CurrentMessageListModel>(context, listen: false)
          .addMessage(key, messageList);
    } catch (err) {
      print(err);
    }
  }

  void onRecvC2CReadReceipt(List<V2TimMessageReceipt> list) {
    print('收到了新消息 已读回执');
    list.forEach((element) {
      print("已读回执${element.userID} ${element.timestamp}");
      Provider.of<CurrentMessageListModel>(context, listen: false)
          .updateC2CMessageByUserId(element.userID);
    });
  }

  void onSendMessageProgress(V2TimMessage message, int progress) {
// 消息进度
    String key;
    if (message.groupID == null) {
      key = "c2c_${message.userID}";
    } else {
      key = "group_${message.groupID}";
    }
    try {
      Provider.of<CurrentMessageListModel>(
        context,
        listen: false,
      ).addOneMessageIfNotExits(
        key,
        message,
      );
    } catch (err) {
      print("error $err");
    }
    print(
        "消息发送进度 $progress ${message.timestamp} ${message.msgID} ${message.timestamp} ${message.status}");
  }

  void
  onFriendListAddedonFriendListDeletedonFriendInfoChangedonBlackListDeleted() async {
    V2TimValueCallback<List<V2TimFriendInfo>> friendRes =
    await TencentImSDKPlugin.v2TIMManager
        .getFriendshipManager()
        .getFriendList();
    if (friendRes.code == 0) {
      List<V2TimFriendInfo> newList = friendRes.data;
      if (newList != null && newList.length > 0) {
        Provider.of<FriendListModel>(context, listen: false)
            .setFriendList(newList);
      } else {
        Provider.of<FriendListModel>(context, listen: false)
            .setFriendList(List.empty(growable: true));
      }
    }
  }

  void onFriendApplicationListAdded(List<V2TimFriendApplication> list) {
    // 收到加好友申请,添加双向好友时双方都会周到这个回调，这时要过滤掉type=2的不显示
    print("收到加好友申请");
    List<V2TimFriendApplication> newlist = List.empty(growable: true);
    list.forEach((element) {
      if (element.type != 2) {
        newlist.add(element);
      }
    });
    if (newlist.isNotEmpty) {
      Provider.of<FriendApplicationModel>(context, listen: false)
          .setFriendApplicationResult(newlist);
    }
  }

  Map<String, V2TimConversation> conversationlistToMap(
      List<V2TimConversation> list) {
    Map<int, V2TimConversation> convsersationMap = list.asMap();
    Map<String, V2TimConversation> newConversation = new Map();
    convsersationMap.forEach((key, value) {
      newConversation[value.conversationID] = value;
    });
    return newConversation;
  }

  ///获取消息列表
  _loadData({loadMore = false,type = 6}) async {
    _loading = true;
    if (!loadMore) {
      pageIndex = 1;
    }
    var currentIndex = pageIndex + (loadMore ? 1 : 0);
    print('loading:currentIndex:$currentIndex');
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = SystemGetMessage();
    request
        .add('page', currentIndex)
        .add('type', type)
        .addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    } else if (result['code'] == 0) {
      List<Map<String, dynamic>> listMap =
      new List<Map<String, dynamic>>.from(result['data']['data']);
      List<MessageEntity> list = List();
      List<int> intList = List();
      for (int i = 0; i < listMap.length; i++) {
        list.add(MessageEntity.fromJson(listMap[i]));
        intList.add(list[i].id);
      }
      editMessageStatus(intList);
      setState(() {
        if (loadMore) {
          if (list.isNotEmpty) {
            //合成一个新数组
            messageList = [...messageList, ...list];
            pageIndex++;
            getMessageCount();
          }
        } else {
          messageList = list;
          getMessageCount();
        }
      });
      Future.delayed(Duration(milliseconds: 1000), () {
        _loading = false;
      });
    }
  }

  ///未读消息置为已读
  editMessageStatus(List<int> intList) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    FormData formData = FormData.fromMap({
     'id': intList
    });
    var dio = new Dio();
    dio.options.headers = {"usertoken": appToken};
    var response ;
    try{
      response = await dio.post("http://119.28.131.94:82/app/system/edit/message/status", data: formData);
      var result = response.data;
      if (result['code'] == -1) {
        TxUtils.showErrorToast('登录失效，请重新登录', context);
        Navigator.pop(context);
        Navigator.of(context).push(MaterialPageRoute(
          builder: (context) {
            return LoginPage(
              arguments: {'loginCode': '-1'},
            );
          },
        ));
      } else if (result['code'] == 0) {
        setState(() {
          getMessageCount();
        });
      }
    }catch(e){
      print(e);
      if(e.response.statusCode == 413){
        TxUtils.showErrorToast('文件太大，无法上传', context);
      }
    }
  }

  ///获取未读消息数
  Future<void> getMessageCount() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = MessageCountRequest();
    request
        .addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    } else if (result['code'] == 0) {
      setState(() {
        messageCountEntity  = MessageCountEntity.fromJson(
                new Map<String, dynamic>.from(result['data']));
      });
    }
  }
}
class ConversionItem extends StatelessWidget {
  ConversionItem({
    this.name,
    this.faceUrl,
    this.lastMessage,
    this.unreadCount,
    this.type,
    this.conversationID,
    this.userID,
  });
  final String name;
  final String faceUrl;
  final V2TimMessage lastMessage;
  final int unreadCount;
  final int type;
  final String conversationID;
  final String userID;
  test1(context) {
    Navigator.push(
      context,
      new MaterialPageRoute(
        builder: (context) => type == 1 ? Conversion(conversationID,userId: userID,) : Conversion(conversationID),
      ),
    );
  }

  String formatTime() {
    int timestamp = lastMessage.timestamp * 1000;
    DateTime time = DateTime.fromMillisecondsSinceEpoch(timestamp);
    DateTime now = DateTime.now();

    if (now.day == time.day) {
      return "${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}:${time.second.toString().padLeft(2, '0')}";
    } else {
      return "${time.month.toString().padLeft(2, '0')}-${time.day.toString().padLeft(2, '0')}";
    }
  }

  ImageProvider getFaceUrl() {
    return (faceUrl == null || faceUrl == '')
        ? type == 1
        ? AssetImage( 'assets/images/person.png')
        : AssetImage( 'assets/images/logo.png')
        : NetworkImage( faceUrl);
  }

  Widget build(BuildContext context) {
    return InkWell(
      onTap: () => {test1(context)},
      child: Container(
        height: 70,
        child: Row(
          children: [
            Container(
              width: 70,
              height: 70,
              child: Padding(
                padding: EdgeInsets.all(11),
                child: PhysicalModel(
                  color: Colors.transparent,
                  borderRadius: BorderRadius.circular(4.8),
                  clipBehavior: Clip.antiAlias,
                  child: CircleAvatar(
                    radius: 50,
                    backgroundImage: getFaceUrl(),
                  ),
                ),
              ),
            ),
            Expanded(
              child: Container(
                height: 70,
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      color: hexToColor("ededed"),
                      width: 1,
                      style: BorderStyle.solid,
                    ),
                  ),
                ),
                child: Column(
                  children: [
                    Container(
                      height: 24,
                      margin: EdgeInsets.only(top: 11),
                      child: Row(
                        children: [
                          Expanded(
                            child: Text(
                              name == null ? "xx" : name,
                              style: TextStyle(
                                color: Color(0xffffffff),
                                fontSize: 18,
                                height: 1,
                              ),
                              textAlign: TextAlign.left,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                          Container(
                            child: Text(
                              formatTime(),
                              textAlign: TextAlign.right,
                              style: TextStyle(
                                  color: Color(int.parse('b0b0b0', radix: 16))
                                      .withAlpha(255),
                                  fontSize: 12),
                            ),
                            width: 105,
                            padding: EdgeInsets.only(right: 16),
                          )
                        ],
                      ),
                    ),
                    Container(
                      height: 20,
                      margin: EdgeInsets.only(top: 2),
                      child: Row(
                        children: [
                          Expanded(
                              child: Text(
                                lastMessage.elemType ==
                                    MessageElemType.V2TIM_ELEM_TYPE_TEXT
                                    ? lastMessage.textElem.text
                                    : lastMessage.elemType ==
                                    MessageElemType
                                        .V2TIM_ELEM_TYPE_GROUP_TIPS
                                    ? '【系统消息】'
                                    : lastMessage.elemType ==
                                    MessageElemType
                                        .V2TIM_ELEM_TYPE_SOUND
                                    ? '【语音消息】'
                                    : lastMessage.elemType ==
                                    MessageElemType
                                        .V2TIM_ELEM_TYPE_CUSTOM
                                    ? '【自定义消息】'
                                    : lastMessage.elemType ==
                                    MessageElemType
                                        .V2TIM_ELEM_TYPE_IMAGE
                                    ? '【图片】'
                                    : lastMessage.elemType ==
                                    MessageElemType
                                        .V2TIM_ELEM_TYPE_VIDEO
                                    ? '【视频】'
                                    : lastMessage.elemType ==
                                    MessageElemType
                                        .V2TIM_ELEM_TYPE_FILE
                                    ? '【文件】'
                                    : lastMessage
                                    .elemType ==
                                    MessageElemType
                                        .V2TIM_ELEM_TYPE_FACE
                                    ? '【表情】'
                                    : '',
                                style: TextStyle(
                                  color: CommonColors.getTextWeakColor(),
                                  fontSize: 14,
                                ),
                              )),
                          Container(
                            child: unreadCount > 0
                                ? PhysicalModel(
                              color: Colors.transparent,
                              borderRadius: BorderRadius.circular(9),
                              clipBehavior: Clip.antiAlias,
                              child: Container(
                                color: CommonColors.getReadColor(),
                                width: 18,
                                height: 18,
                                child: Column(
                                  mainAxisAlignment:
                                  MainAxisAlignment.center,
                                  crossAxisAlignment:
                                  CrossAxisAlignment.center,
                                  children: [
                                    Text(
                                      unreadCount > 99
                                          ? '...'
                                          : unreadCount.toString(),
                                      textAlign: TextAlign.center,
                                      textWidthBasis:
                                      TextWidthBasis.parent,
                                      style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 12,
                                        fontWeight: FontWeight.w500,
                                      ),
                                    )
                                  ],
                                ),
                              ),
                            )
                                : null,
                            width: 18,
                            height: 18,
                            margin: EdgeInsets.only(right: 16),
                          )
                        ],
                      ),
                    )
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
